#include "headers.h"

//typedef pthread_mutex_t* CMS_OS_MUTEX;
CMS_OS_MUTEX cms_os_mutex_create()
{
	return ::CreateMutex(NULL, FALSE, NULL);
}

void cms_os_mutex_delete(CMS_OS_MUTEX m)
{
	::CloseHandle(m);
}

void cms_os_mutex_lock(CMS_OS_MUTEX m)
{
	::WaitForSingleObject(m, INFINITE);
}

void cms_os_mutex_unlock(CMS_OS_MUTEX m)
{
	::ReleaseMutex(m);
}

cms_os_mutex_wrapper::cms_os_mutex_wrapper(CMS_OS_MUTEX mutex)
{
	m_mutex = mutex;
	cms_os_mutex_lock(mutex);
}

cms_os_mutex_wrapper::~cms_os_mutex_wrapper()
{
	cms_os_mutex_unlock(m_mutex);
}

string cms_os_generateId(string serviceName)
{
	static CMS_OS_MUTEX mutex = cms_os_mutex_create();
	static int count = 0;
	char buf[1024];

	int tid = GetCurrentThreadId();
	int pid = GetCurrentProcessId();

	{
		cms_os_mutex_wrapper guard(mutex);
		count ++;
		tid += count;
		pid += tid * count;
	}

	sprintf(buf, "%s_%x_%x", serviceName.c_str(), tid, pid);
	return buf;
}

